/*
 * File:    Math.java
 * Created: 04-Mar-2009
 * Version: $Id$
 *
 * COPYRIGHT (C) 2009, Bitgate Mobile, LLC.  All Rights Reserved.
 *
 * software@bitgatemobile.com
 */

package com.webplasm.render.tags.u;

import java.util.Arrays;
import java.util.List;
import java.util.UUID;

import org.nfunk.jep.JEP;

import com.webplasm.context.RenderContext;
import com.webplasm.render.engine.RenderException;
import com.webplasm.render.tags.TagInterface;
import com.webplasm.render.tags.WrappedNode;
import com.webplasm.store.VariableStoreInterface;
import com.webplasm.store.VariableContainer.VariableType;

public class Math extends WrappedNode implements TagInterface {
	private static final String DESCRIPTION = "Evaluates and returns the result of a mathematical expression.";

	public String getNamespace() {
		return "u";
	}
	
	public List<String> getAttributes() {
		return Arrays.asList("var");
	}
	
	public List<String> getManagedNodes() {
		return null;
	}

	public String getDescription() {
		return DESCRIPTION;
	}

	@Override
	public StringBuffer render(RenderContext rContext) throws RenderException {
		if (elements.get("var") != null) {
			if (elements.get("var").equals("server_uuid")) {
				return new StringBuffer(UUID.randomUUID().toString());
			}
		}
		
		JEP jep = new JEP();
		
		jep.addStandardConstants();
		jep.addStandardFunctions();
		jep.addComplex();
		jep.parseExpression(super.render(rContext).toString());
		
		if (elements.get("var") != null) {
			VariableStoreInterface vsInterface = rContext.getVariableStore().getVariable(elements.get("var"), VariableType.STRING);

			vsInterface.setValue(Double.toString(jep.getValue()));
			
			return new StringBuffer();
		}
		
		return new StringBuffer(Double.toString(jep.getValue()));
	}
}